package com.sinoparasoft.lilac.service;

import java.util.Date;
import java.util.Properties;

import javax.mail.Authenticator;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;

import com.sinoparasoft.lilac.model.Mail;


public class MailSender {
	private Session session;	
	private final String SMTP_HOST = "mail.smtp.host";
    private final String SMTP_AUTH = "mail.smtp.auth";
    private final String username = "xiangqian@iscas.ac.cn";
    private final String password = "lg82ac69";
    private final String host = "smtp.cstnet.cn";
    private final String from = "feedback@lpscs.local";
    private final String recipient = "xiangqian@iscas.ac.cn";
	
	public MailSender() {
		init();
	}
	
	public void send(Mail mail, boolean debug) {
	       // 有了这句便可以在发送邮件的过程中在console处显示过程信息，供调试使用
	       session.setDebug(debug);

	       try {
		   		MimeMessage message = new MimeMessage(session);
				message.setFrom(new InternetAddress(from));
				message.setSentDate(new Date());
				message.addRecipient(Message.RecipientType.TO, new InternetAddress(recipient));
				message.setSubject(mail.getSubject());
				message.setContent(mail.getContent(), "text/html;charset=utf-8");
				
	           Transport.send(message);
	       } catch (AddressException e) {
	           e.printStackTrace();
	       } catch (MessagingException e) {
	           e.printStackTrace();
	       }
	    }
	
	private void init() {
		Authenticator auth = new Authenticator() {
			protected PasswordAuthentication getPasswordAuthentication() {
				return new PasswordAuthentication(username, password);
			}
		};

		Properties props = new Properties();
		// 设置发送邮件的邮件服务器的属性
		props.put(SMTP_HOST, host);
		// 需要经过授权，也就是有户名和密码的校验，这样才能通过验证（一定要有这一条）
		props.put(SMTP_AUTH, "true");
		// 用刚刚设置好的props对象构建一个session
		session = Session.getDefaultInstance(props, auth);
	}
}
